<template>
    <el-container style="height: 100%;">
        <el-header style="height: 0.6rem">
            <common-header></common-header>
        </el-header>
        <el-container class="main">
            <el-tabs v-model="activeName" @tab-click="handleClick" type="card">
                <el-tab-pane class="base-service" label="基础服务" name="first">
                    <div class="base-service-table-div">
                        <el-table :data="baseServiceTableData" ref="baseTable">
                            <el-table-column prop="ServerName" label="名称" width="180"></el-table-column>
                            <el-table-column prop="State" label="状态" width="180">
                                <template slot-scope="node">
                                    <span
                                        class="region-label"
                                        :class="node.row.StateStr == '运行' ? 'label-green' : node.row.StateStr == '启动中' ? 'label-blue' : node.row.StateStr == '停止' ? 'label-red' : '' "
                                    >{{node.row.StateStr}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="PID" label="进程ID"></el-table-column>
                            <el-table-column prop="Port" label="端口号"></el-table-column>
                            <el-table-column prop="CreateTime" label="启动时间"></el-table-column>
                            <el-table-column prop="RunTime" label="运行时长"></el-table-column>
                            <el-table-column label="操作">
                                <template slot-scope="scope">
                                    <el-button type="success" plain @click="baseLaunchClick(scope.row)" size="mini">启动</el-button>
                                    <el-button type="danger" plain @click="baseStopClick(scope.row)" size="mini">停止</el-button>
                                    <el-button type="warning" plain @click="baseRestartClick(scope.row)" size="mini">重启</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-tab-pane>
                <el-tab-pane class="sys-service" label="系统服务" name="second">
                    <div class="sys-service-tool">
                        <el-button type="success" @click="allStartClick">全部启动</el-button>
                        <el-button type="danger" @click="allStopClick">全部停止</el-button>
                        <el-button type="warning" @click="allRestartClick">全部重启</el-button>
                    </div>
                    <div class="sys-service-table">
                        <el-table :data="sysServiceTableData.slice((currentPage1-1)*pageSize,currentPage1*pageSize)" :fit="true" ref="sysTable">
                            <el-table-column prop="Name" label="名称"></el-table-column>
                            <el-table-column prop="StateStr" label="状态">
                                <template slot-scope="node">
                                    <span
                                        class="region-label"
                                        :class="node.row.StateStr == '运行中' ? 'label-green' : node.row.StateStr == '启动中' ? 'label-blue' : node.row.StateStr == '停止' ? 'label-red' : '' "
                                    >{{node.row.StateStr}}</span>
                                </template>
                            </el-table-column>
                            <el-table-column prop="PID" label="进程ID"></el-table-column>
                            <el-table-column prop="Port" label="端口号"></el-table-column>
                            <el-table-column prop="CreateTime" label="启动时间" width="250"></el-table-column>
                            <el-table-column prop="RunTime" label="运行时长"></el-table-column>
                            <el-table-column prop="Xms" label="堆内存(Xms)"></el-table-column>
                            <el-table-column prop="Xmx" label="栈内存(Xmx)"></el-table-column>
                            <el-table-column prop="Cpu" label="CPU"></el-table-column>
                            <el-table-column prop="Ram" label="内存"></el-table-column>
                            <el-table-column label="操作" width="400">
                                <template slot-scope="scope">
                                    <el-button type="success" plain @click="sysLaunchClick(scope.row)" size="mini">启动</el-button>
                                    <el-button type="danger" plain @click="sysStopClick(scope.row)" size="mini">停止</el-button>
                                    <el-button type="warning" plain @click="sysRestartClick(scope.row)" size="mini">重启</el-button>
                                    <el-button type="primary" plain @click="sysRunParamClick(scope.row)" size="mini">运行参数</el-button>
                                    <el-button type="primary" plain @click="sysLogClick(scope.row)" size="mini">服务日志</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                        <div class="tabListPage">
                            <el-pagination
                                background
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="currentPage1"
                                :page-sizes="[10, 20, 30, 40]"
                                :page-size="pageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                :total="total"
                            ></el-pagination>
                        </div>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="系统日志" name="third">
                    <sys-log @changeDate="selectDateFunc" :dateTime="dateVal" :logData="sysLogData"></sys-log>
                </el-tab-pane>
            </el-tabs>

            <!-- 服务日志 -->
            <el-dialog
                class="sysLogDialog"
                title="服务日志"
                :visible.sync="dialogSysLogVisible"
                :close-on-click-modal="false"
                modal
                @close="sysLogParam = { logData : '',toolBtn:''}"
            >
                <div class="sys-log-tool">
                    <el-button-group class="tool-group">
                        <el-button class="tool-btn" :class="sysLogParam.toolBtn === 'Debug' ? 'act': ''" autofocus @click="getLogClick('Debug')">Debug</el-button>
                        <el-button class="tool-btn" :class="sysLogParam.toolBtn === 'Error' ? 'act': ''" @click="getLogClick('Error')">Error</el-button>
                    </el-button-group>
                    <el-button icon="el-icon-refresh" @click="getLogClick(null)"></el-button>
                </div>
                <div class="sys-log-text">
                    <div class="log-info-item" v-for="item in sysLogParam.logData" :key="item.id">
                        <span>{{item}}</span>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogSysLogVisible = false">取消</el-button>
                </div>
            </el-dialog>
            <!-- 运行参数 -->
            <el-dialog class="sysRunParamDialog" title="运行参数" :visible.sync="dialogSysRunParamVisible" :close-on-click-modal="false" modal>
                <el-form :model="sysRunParamForm">
                    <el-form-item label="端口号" label-width="100px" class="port-item">
                        <el-input v-model="sysRunParamForm.port" autocomplete="off"></el-input>
                        <el-button type="primary" class="detection" @click="portCheckClick">检测</el-button>
                    </el-form-item>
                    <el-form-item label="优先级" label-width="100px">
                        <el-input v-model="sysRunParamForm.order" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="启动参数" label-width="100px">
                        <el-input type="textarea" rows="8" class="startParam" v-model="sysRunParamForm.jvmArgs" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="updateServerConfig">确认</el-button>
                    <el-button @click="dialogSysRunParamVisible = false">取消</el-button>
                </div>
            </el-dialog>
        </el-container>
    </el-container>
</template>

<script>
import CommonHeader from '@/components/CommonHeader.vue';
import SysLog from '@/views/system/SysLog.vue';
import {
    getListAllBasic,
    startBasicServer,
    stopBasicServer,
    reStartBasicServer,
    getListAllSys,
    startSysServer,
    stopSysServer,
    reStartSysServer,
    getSystemServerLog,
    getServerConfig,
    updateServerConfig,
    getSystemServerRunLog,
    isPortUsed,
} from '@/api/data';
export default {
    name: 'newHome',
    components: {
        CommonHeader,
        SysLog,
    },
    data() {
        return {
            activeName: 'first',
            baseServiceTableData: [],
            sysServiceTableData: [],
            dialogSysLogVisible: false, // 系统服务日志窗口
            sysLogParam: {
                serverName: '',
                toolBtn: '',
                logData: '',
            },
            dialogSysRunParamVisible: false, // 运行参数窗口
            sysRunParamForm: {
                serverName: '',
                port: 0,
                order: 0,
                jvmArgs: '',
            },
            sysLogData: [],
            dateVal: '',
            isRenderBase: true,
            isRenderSys: true,
            isRenderDate: true,
            currentPage1: 1, //默认显示第一页
            total: 20, //这是总是开始可以直接赋值为空都可以
            pageSize: 10, //每页显示多少条
        };
    },
    methods: {
        handleClick(tab) {
            if (tab.name === 'first' && this.isRenderBase) {
                this.getBaseData();
                this.isRenderBase = false;
            } else if (tab.name === 'second' && this.isRenderSys) {
                this.getSysServiceList();
                this.isRenderSys = false;
            } else if (tab.name === 'third' && this.isRenderDate) {
                this.selectDateFunc(this.dateVal);
                this.isRenderDate = false;
            }
            this.$nextTick(() => {
                //在数据加载完，重新渲染表格
                this.$refs.baseTable.doLayout();
                this.$refs.sysTable.doLayout();
            });
        },
        // 基础服务 获取列表
        async getBaseData() {
            await getListAllBasic().then((data) => {
                this.baseServiceTableData = data;
            });
        },
        // 基础服务 启动
        baseLaunchClick(row) {
            this.$confirm('确定启动吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    startBasicServer(row).then(() => {
                        this.$message({
                            message: '命令发送成功',
                            type: 'success',
                        });
                    });
                })
                .catch(() => {});
        },
        // 基础服务 停止
        baseStopClick(row) {
            this.$confirm('确定停止吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    stopBasicServer(row).then(() => {
                        this.$message({
                            message: '命令发送成功',
                            type: 'success',
                        });
                    });
                })
                .catch(() => {
                    //取消
                });
        },
        // 基础服务 重启
        baseRestartClick(row) {
            this.$confirm('确定重启吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    reStartBasicServer(row).then(() => {
                        this.$message({
                            message: '命令发送成功',
                            type: 'success',
                        });
                    });
                })
                .catch(() => {
                    //取消
                });
        },
        // 获取系统服务列表
        async getSysServiceList() {
            await getListAllSys().then((data) => {
                this.sysServiceTableData = data;
                this.total = this.sysServiceTableData.length;
            });
        },
        // 系统服务 分页
        handleSizeChange(val) {
            //一页显示多少条
            this.pageSize = val;
        },
        // 系统服务 分页
        handleCurrentChange(val) {
            //默认第一页，当你点击就把点击的那页赋值给currentPage1
            this.currentPage1 = val;
        },
        // 系统服务 全部启动
        allStartClick() {
            this.$confirm('确定全部启动吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    startSysServer({ ServerName: 'all' }).then(() => {
                        this.$message({
                            message: '命令发送成功',
                            type: 'success',
                        });
                    });
                })
                .catch(() => {
                    //取消
                });
        },
        // 系统服务 全部停止
        allStopClick() {
            this.$confirm('确定全部停止吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    stopSysServer({ ServerName: 'all' }).then(() => {
                        this.$message({
                            message: '命令发送成功',
                            type: 'success',
                        });
                    });
                })
                .catch(() => {
                    //取消
                });
        },
        // 系统服务 全部重启
        allRestartClick() {
            this.$confirm('确定全部重启吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    reStartSysServer({ ServerName: 'all' }).then(() => {
                        this.$message({
                            message: '命令发送成功',
                            type: 'success',
                        });
                    });
                })
                .catch(() => {
                    //取消
                });
        },
        // 系统服务 启动
        sysLaunchClick(row) {
            this.$confirm('确定启动吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    startSysServer(row).then(() => {
                        this.$message({
                            message: '命令发送成功',
                            type: 'success',
                        });
                    });
                })
                .catch(() => {
                    //取消
                });
        },
        // 系统服务 停止
        sysStopClick(row) {
            this.$confirm('确定停止吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    stopSysServer(row).then(() => {
                        this.$message({
                            message: '命令发送成功',
                            type: 'success',
                        });
                    });
                })
                .catch(() => {
                    //取消
                });
        },
        // 系统服务 重启
        sysRestartClick(row) {
            this.$confirm('确定重启吗？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(() => {
                    reStartSysServer(row).then(() => {
                        this.$message({
                            message: '命令发送成功',
                            type: 'success',
                        });
                    });
                })
                .catch(() => {
                    //取消
                });
        },
        // 系统服务 查询运行参数
        sysRunParamClick(row) {
            this.dialogSysRunParamVisible = true;
            this.sysRunParam(row);
        },
        async sysRunParam(row) {
            await getServerConfig(row).then((data) => {
                this.sysRunParamForm.serverName = data.ServerName;
                this.sysRunParamForm.port = data.Port;
                this.sysRunParamForm.order = data.Order;
                this.sysRunParamForm.jvmArgs = data.JvmArgs;
            });
        },
        // 系统服务 更新运行参数
        updateServerConfig() {
            let exp1 = /^([1-9](\d{0,3}))$|^([1-5]\d{4})$|^(6[0-4]\d{3})$|^(65[0-4]\d{2})$|^(655[0-2]\d)$|^(6553[0-5])$/;
            if (!exp1.test(this.sysRunParamForm.port)) {
                this.$message({
                    message: '端口需要是0-65535的正整数',
                    type: 'warning',
                });
                return false;
            }
            let exp2 = /^[1-9]\d*$/;
            if (!exp2.test(this.sysRunParamForm.order)) {
                this.$message({
                    message: '优先级需要大于0的正整数',
                    type: 'warning',
                });
                return false;
            }
            let params = {
                ServerName: this.sysRunParamForm.serverName,
                Port: this.sysRunParamForm.port,
                Order: this.sysRunParamForm.order,
                JvmArgs: this.sysRunParamForm.jvmArgs,
            };
            updateServerConfig(params).then(() => {
                this.$message({
                    message: '命令发送成功',
                    type: 'success',
                });
            });
        },
        // 系统服务 检测端口
        portCheckClick() {
            isPortUsed({ Port: this.sysRunParamForm.port }).then((data) => {
                if (data) {
                    this.$message({
                        message: '端口被占用',
                        type: 'warning',
                    });
                } else {
                    this.$message({
                        message: '端口正常',
                        type: 'success',
                    });
                }
            });
        },
        // 系统服务 服务日志
        sysLogClick(row) {
            this.sysLogParam.serverName = row.ServerName;
            this.dialogSysLogVisible = true;
            // this.getLogClick('Debug');
        },
        async getLogClick(logLevel) {
            console.log(this.$refs[logLevel]);
            if (logLevel == null) {
                if (this.sysLogParam.toolBtn == '') {
                    this.$message({
                        message: '请选择日志类型',
                        type: 'warning',
                    });
                    return false;
                } else if (this.sysLogParam.toolBtn != '') {
                    logLevel = this.sysLogParam.toolBtn;
                }
            }
            this.sysLogParam.toolBtn = logLevel;
            let params = {
                ServerName: this.sysLogParam.serverName,
                logLevel: logLevel,
            };
            await getSystemServerRunLog(params).then((res) => {
                if (res) {
                    this.sysLogParam.logData = res.split('\n');
                }
            });
        },
        // 系统日志
        async selectDateFunc(data) {
            if (data) {
                let params = { date: data };
                await getSystemServerLog(params).then((res) => {
                    if (res) {
                        this.sysLogData = res;
                    }
                });
            } else {
                this.sysLogData = [];
            }
        },
    },
    created() {
        this.getBaseData();
        let date = new Date(),
            year = date.getFullYear().toString(),
            month = date.getMonth() + 1,
            day = date.getDate().toString();
        this.dateVal = `${year}-${month.toString().padStart(2, '0')}-${day.padStart(2, '0')}`;
    },
};
</script>
 
<style lang="scss" scoped>
.el-header {
    padding: 0 0.38rem;
    background: #347aeb;
}
.main {
    padding: 0.05rem;
    // height: 100%;
    box-sizing: border-box;
    height: 100%;
    overflow: hidden;
    ::v-deep .el-tabs {
        height: 100%;
        .label-blue {
            color: #347aeb;
        }
        .label-green {
            color: #24b447;
        }
        .label-red {
            color: #ff5e5e;
        }
        .el-tabs__header {
            height: 0.42rem !important;
        }
        .el-table {
            .el-button--success {
                color: #24b447;
                background-color: rgba(36, 180, 71, 0.1);
                border: none;
            }
            .el-button--danger {
                color: #ff5e5e;
                background-color: rgba(255, 94, 94, 0.1);
                border: none;
            }
            .el-button--warning {
                color: #fda83f;
                background-color: rgba(253, 168, 63, 0.1);
                border: none;
            }
            .el-button--primary {
                color: #467cd4;
                background-color: #e3ebf9;
                border: none;
            }
        }

        .el-tabs__content {
            height: calc(100% - 0.42rem);
            box-sizing: border-box;
            .el-tab-pane {
                height: 100%;
                padding: 0.15rem 0;
                box-sizing: border-box;
            }
            .base-service {
                padding: 0.13rem 0.3rem 0 0.29rem;
                .base-service-table-div {
                    height: calc(100% - 0.12rem);
                    .el-table {
                        height: 100%;
                        .is-scrolling-none {
                            overflow-y: auto;
                            height: 100%;
                        }
                    }
                }
            }
            .sys-service {
                padding: 0.14rem 0.3rem 0 0.29rem;
                .sys-service-tool {
                    display: flex;
                    justify-content: flex-end;
                }
                .sys-service-table {
                    padding-top: 0.22rem;
                    height: calc(100% - 1.7rem);
                    .el-table {
                        height: 100%;
                        .is-scrolling-none {
                            overflow-y: auto;
                            height: 100%;
                        }
                    }
                    .tabListPage {
                        display: flex;
                        justify-content: flex-end;
                        padding-top: 0.18rem;
                        .el-pagination {
                            display: flex;
                            align-items: center;
                            .el-pagination__sizes {
                                height: 0.3rem;
                            }
                            .el-input__inner {
                                height: 0.3rem;
                            }
                        }
                    }
                }
            }
        }
    }
}
.sysLogDialog {
    ::v-deep .el-dialog {
        width: 14.21rem;
        height: 7.54rem;
        .sys-log-tool {
            padding-bottom: 0.2rem;
            display: flex;
            justify-content: space-between;
            position: relative;
            .tool-btn {
                position: relative;
                &:focus {
                    background-color: #fff;
                    color: #347aeb;
                    border: 1px solid #e1e1e1;
                }
            }
            .act::after {
                content: '';
                position: absolute;
                height: 0.04rem;
                bottom: 0px;
                background-color: #347aeb;
                width: 0.31rem;
                left: 0.31rem;
            }
        }
        .sys-log-text {
            width: 13.81rem;
            height: 5.09rem;
            border: 1px solid #e5e5e5;
            overflow-y: auto;
            overflow-x: hidden;
        }
    }
}
.sysRunParamDialog {
    ::v-deep .el-dialog {
        width: 6.25rem;
        height: 5.15rem;
        .el-select .el-input {
            width: 4.54rem;
            height: 0.35rem;
        }
        .el-input {
            width: 4.54rem;
            height: 0.35rem;
        }
        .el-textarea {
            width: 4.54rem;
        }
        .port-item {
            position: relative;
            .detection {
                position: absolute;
                right: 0.35rem;
                width: 0.7rem;
                height: 0.29rem;
                background-color: #347aeb;
                top: 0.05rem;
                display: flex;
                align-items: center;
            }
        }
    }
}
</style>